package com.aplana.ccsd.service;

import info.magnolia.jcr.util.PropertyUtil;
import info.magnolia.module.blossom.dialog.TabBuilder;
import info.magnolia.module.templatingkit.dam.Asset;

import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aplana.ccsd.model.Area;
import com.aplana.ccsd.model.Promo;
import com.aplana.ccsd.util.DialogUtils;
import com.aplana.ccsd.util.JcrNodeUtils;

@Service
public class PromoServiceImpl implements PromoService {
	
	@Autowired
	private TemplatingService templatingService;
	
	@Override
	public Promo getPromo(Node promoComponent) throws PathNotFoundException, RepositoryException {
		String promoLink = PropertyUtil.getString(promoComponent, "promoLink");
		Asset promoImage =  templatingService.getNodePropertyAsImage(promoComponent, "promoImage");
		Node promoPage = promoComponent.getSession().getNode(
				promoLink);
		
		return new Promo(JcrNodeUtils.getURL(promoPage), promoImage);
	}

	@Override
	public void addPromoDialogControls(TabBuilder tabBuilder) {
		tabBuilder.addLink("promoLink", "Страница c описанием", "Ссылка на страницу с описанием рекламы");
		DialogUtils.addDamControl(tabBuilder, "promoImage", "Картинка с рекламой", "");
	}

	@Override
	public void addPromosAreaDialogControls(TabBuilder tabBuilder) {
		tabBuilder.addEdit("containerWidth", "Ширина контейнера", "Ширина контейнера в px");
	}

	@Override
	public Area getPromosArea(Node promosArea) throws PathNotFoundException,
			RepositoryException {
		String containerWidth = PropertyUtil.getString(promosArea, "containerWidth");
		Integer conWidth = null; // по умолчанию
		if (!org.apache.commons.lang.StringUtils.isBlank(containerWidth)) {
			conWidth = Integer.decode(containerWidth);
		}
		return new Area(conWidth);
	}

}